clc;
clear;
global num_firm T_sim S T n_theta beta n_tran tau mktfe search T_cal country_num rho_par  phi



%% solve + simulation
num_firm = 11000; %11575
T_sim = 240; % simulated periods, need to drop first a few
T_cal = 96; %week result
S = 10; % number of realizations
T = 25; % after T periods, it's full learning
n_theta = 100; % # of possible firm draws
%sigma = 2500; % mark up
beta = 0.999;
rho_par = 2.41;
n_tran = 100; % discretize firm state for each firm
input = csvread('~\country-fe.csv',1,1);
%input = input(3,:);
search = input(:,1);
%search = 1;
mktfe = input(:,2);
tau = input(:,3);
%tau = zeros(size(tau));
phi = input(:,4);
country_num = size(search,1);
%mktfe = ones(country_num,1)*10000;

rand('seed',0);
replace_sim = rand(num_firm,T_sim,S);
rand('seed',1);
country_sim = rand(num_firm,T_sim,S);
country_search = nan(size(country_sim));
rand('seed',2);
exit_sim = rand(num_firm,T_sim,S);
rand('seed',3);
purchase_sim = rand(num_firm,T_sim,S);
rand('seed',4);
ads_sim = rand(num_firm,T_sim,S);
rand('seed',5);
feedback_sim = rand(num_firm,T_sim,S);

% convert country sim to country ind directly

 for j = 1:S
       country_search(:,:,j) = transform(repmat(search,1,num_firm),country_sim(:,:,j)'); 
 end;



SIM = struct('sim_matrix_num',6);
SIM.replace = replace_sim;
SIM.country = country_search;
SIM.exit = exit_sim;
SIM.purchase = purchase_sim;
SIM.ads = ads_sim;
SIM.feedback = feedback_sim;

%% minimization
weight = 10000;
ObjectiveFunction = @(x) object(x,SIM,weight);
options_use = saoptimset('display','iter','DisplayInterval',1,'MaxFunEvals',10000,'MaxIter',10000,'ObjectiveLimit',0.01,'TolFun',0.001);
%    ave_theta    h_theta    h_eps        delta         cost   gamma 
    x0 = [   -8.7699     -0.96234      0.59034       1.9198];%[8.3040    8.7231   -0.4778   -6.3277] nan
        lb = [-10         -10     -10     -10 ];
        ub = [10          10      10        10 ];
     [x,fval, exitflag, output] = simulannealbnd(ObjectiveFunction,x0,lb,ub,options_use);
